var member_id = member_name = store_id = pay_name = shuju = address_id = buy_city_id = '';
var ifcart = vat_hash = offpay_hash = offpay_hash_batch = '';
var ws = flea = goods_id = uid = '';
document.addEventListener('plusready',function(){
	ws = plus.webview.currentWebview();
	shuju = ws.shuju;
	pay_name = ws.payment_type;
	ifcart = ws.ifcart;
	store_ids = ws.store_id;
	flea = ws.flea;
	uid = ws.uid;
	member_id = plus.storage.getItem('id');
	store_id = plus.storage.getItem('store_id');
	member_name = plus.storage.getItem('name');
	if(flea == 'flea'){
		$('.flea').removeClass('Good');
	}else{
		$('.Good').removeClass('flea');
	}
	console.log(member_id);
	goods_inf();

	$('.Good').on('click',function(){
		 var remarks = $('.remarks').val();
//		 console.log(shuju+'--'+address_id+'--'+pay_name+'--'+member_id+'--'+remarks+'--'+vat_hash+'--'+offpay_hash+'--'+offpay_hash_batch);
		 if(!store_ids){
		 	store_ids = $('.stoar').each(function(){
		 		var _this = $(this);
		 		store_ids += _this.attr('data-stoar_id'); 
		 	});
		 }   
		 $.ajax({  
		 	type:"post",
		 	url:apiRoot + "?act=member_buy&op=buy_step2", 
		 	data:{
		 		cart_id:shuju,
		 		address_id:address_id,
		 		pay_name:pay_name,
		 		member_id:member_id,
		 		pay_message:remarks,
		 		vat_hash:vat_hash,
		 		offpay_hash:offpay_hash,
		 		offpay_hash_batch:offpay_hash_batch,
		 		ifcart:ifcart,
		 		ordertype:1
		 	}, 
		 	dataType:'json', 
		 	success:function(data){
//		 		console.log(JSON.stringify(data));
		 		if(data.state){
		 			$('.payment').attr('pay_sn',data.pay_sn);
	 				$('.payment').attr('order_id',data.order_key_id);
		 			$('.popover').show();
					$('.btn').slideDown();
		 		}else{
		 			toast(data.datas.error);
		 		}
		 	},
		 	error:function(e){
		 		console.log(JSON.stringify(e));
		 	}
		 });
	})
	
	
	
	//付款
	$('.flea').on('click',function(){
		var _this = $(this);
		var money = $('.goods_total').text();   //订单id
		var endtime=new Date();
		var order_py = endtime.getTime();
		plus.nativeUI.actionSheet({cancel:"取消",buttons:[{title:"余额支付"},{title:"支付宝支付"},{title:"微信支付"}]},function(e){
			if(e.index == 1){
				$('.password-of-pay-wraper').css("display","block");
				$('#password_backdrop').css("display","block");
				$('.btn').slideUp()				
				
				//如果用户选择的是余额支付，则执行如下代码
				tool.shade(function (){
					$("#j_password_of_pay").hide();
				}).show();
				//默认让第一个输入框获得焦点
				setTimeout(function (){
					$("#j_password_of_pay").show().find("input:password").eq(0).focus();
				},10); 
				var pwdInputs = $("#j_password_of_pay input:password");
				pwdInputs.each(function (index,item){
					$(this).on("keyup",function (){
						if(!tool.isEmpty($(this).val())){
							$(this).next().focus();
							//如果是最后一个输入框，则执行ajax操作
							if(index == pwdInputs.size() - 1){
								var pwd = "";
								$(this).blur();
								pwdInputs.each(function (){
									pwd += $(this).val();
								});
								yuezhifu_flea(money,pwd); 
//									alert("用户输入的密码是："+ pwd +"，发送ajax，检查用户输入密码是否正确");	
//									$("#j_password_of_pay").hide();
//									tool.shade().hide();
//									$('.popover').fadeOut();
							}
						}
					});
				});
			}else if(e.index == 2){
				ptype = 'alipay';
				payment(order_py,money);
			}else if(e.index == 3){
				ptype = 'wxpay'; 
				payment(order_py,money);
			}else{
				toast("取消支付,订单已生成！");
				ws.close();
			}	
		});
		
	})
	
	
},false)

function myaddr(){
	var nwaiting = plus.nativeUI.showWaiting();//显示原生等待框
	var webviewContent= plus.webview.create('my-addr.html','my-addr.html',{},{spage:ws.id});//后台创建webview并打开show.html
	webviewContent.addEventListener("loaded", function() { //注册新webview的载入完成事件
        nwaiting.close(); //新webview的载入完毕后关闭等待框
        webviewContent.show("slide-in-right",500); //把新webview窗体显示出来，显示动画效果为速度200毫秒的右侧移入动画
	}, false);
}

function goods_inf(){
	console.log(shuju); 
	$.ajax({ 
		type:"post",
		url:apiRoot + "?act=member_buy&op=buy_step1",
		data:{
			member_id:member_id,
			cart_id:shuju,
			ifcart:ifcart
		},
		dataType:'json',
		success:function(data){
			console.log(JSON.stringify(data));
			if(data){
				if(data.code == 400){
					toast(data.datas.error);
					ws.close();
					return;
				}
				if(data.store_ids.length > 0){ 
					var html = '';
					var goods_total = goods_freight = 0;
					$.each(data.store_ids, function(k1,v1) {  
						$.each(data.store_cart_list[v1].goods_list, function(k,v) {
							goods_freight = goods_freight + parseFloat(v.goods_freight);
							goods_total = goods_total + (parseFloat(v.goods_price) * parseFloat(v.goods_num));
							html += '<ul class="mui-table-view stoar" data-stoar_id="'+ v.store_id +'">'+
										'<li class="mui-table-view-cell mui-media">'+
											'<a href="javascript:;">'+
												'<img class="mui-media-object mui-pull-left goods_image" src="'+ pics + v.store_id + '/' + v.goods_image +'">'+
												'<div class="mui-media-body">'+
													'<div class="mui-ellipsis-2 goods_name">'+ v.goods_name +'</div>'+
													'<p class="mui-ellipsis1" style="padding: 3px 0 9px;">'+
														'<span class="goods_spec">'+ (v.goods_spec?v.goods_spec:"") +'</span>'	+						
													'</p>'+
													'<p class="botm">'+
														'<b class="red">￥<span class="goods_price">'+ v.goods_price +'</span></b>'+
														'<span class="font10 mui-pull-right gray goods_num">x'+ v.goods_num +'</span>'+
													'</p>'+
												'</div>'+
											'</a>'+
										'</li>'+
									'</ul>';
						})	
					});
					$('.goods_list').html(html);
					
					if(ifcart == '1'){
						$('.goods_total').text(data.order_amount); 
					}else{ 
						$('.goods_freight').text(goods_freight);
						$('.goods_total').text((goods_total + goods_freight).toFixed(2));
					}
						
				}
				if(data.address_info.address_id > 0){
					$('.true_name').text('收货人：'+data.address_info.true_name);
					$('.mob_phone').text(data.address_info.mob_phone);
					$('.address').text('收货地址：'+data.address_info.area_info+ ' ' +data.address_info.address);
					address_id = data.address_info.address_id;
					buy_city_id = data.address_info.city_id;
					vat_hash = data.vat_hash; 
			 		offpay_hash = data.address_api.offpay_hash;
			 		offpay_hash_batch = data.address_api.offpay_hash_batch; 
				}else{
					$('.address').text('你还没有设置默认地址！'); 
					vat_hash = data.vat_hash;  
				}
			}
		}, 
		error:function(e){
			console.log(JSON.stringify(e));
			error();
			ws.close();
		}
	});
}

function yuezhifu_flea(money,paypass){
//	console.log(member_id +"==="+order_id);
	$.ajax({ 
		type:"post",
		url:apiRoot + "?act=member_buy&op=payment_flea",
		data:{
			member_id:member_id,
			money:money,
			paypass:paypass
		},  
		dataType:'json', 
		success:function(data){
//			console.log(JSON.stringify(data));
			if(data.code == 200){
//				toast('支付成功！');
				//隐藏支付密码框
				$("#j_password_of_pay").hide();
				tool.shade().hide();
				$('.popover').fadeOut();
				$('#password_backdrop').css("display","none");
				order_start(money);
			}else{
//				toast(data.datas.error);
				if(data.datas.error == '余额不足，生成订单失败！'){
					toast(data.datas.error);
					//隐藏支付密码框
					$("#j_password_of_pay").hide();
					tool.shade().hide();
					$('.popover').fadeOut();
					$('#password_backdrop').css("display","none");
				}else{
					toast(data.datas.error);
					$('.mui-clearfix input').val('');
				}
			} 
		},
		error:function(e){
			error();
		}
	});
}

function order_start(price){
	var remarks = $('.remarks').val();
//		 console.log(shuju+'--'+address_id+'--'+pay_name+'--'+member_id+'--'+remarks+'--'+vat_hash+'--'+offpay_hash+'--'+offpay_hash_batch);
	 $.ajax({  
	 	type:"post",
	 	url:apiRoot + "?act=member_buy&op=buy_step2", 
	 	data:{
	 		cart_id:shuju,
	 		address_id:address_id,
	 		pay_name:pay_name,
	 		member_id:member_id,
	 		pay_message:remarks,
	 		vat_hash:vat_hash,
	 		offpay_hash:offpay_hash,
	 		offpay_hash_batch:offpay_hash_batch,
	 		ifcart:ifcart,
	 		flag:1,                  //根据此值直接添加订单状态为已付款       跳蚤商品
	 		ordertype:4,
	 		price:price,				//支付金额
	 		uid:uid						//收款人
	 	},
	 	dataType:'json',
	 	success:function(data){
		 		console.log(JSON.stringify(data));
	 		if(data.state){
	 			toast('支付成功！');
	 			commodity_shelf();
	 			var nwaiting = plus.nativeUI.showWaiting();//显示原生等待框
				var webviewContent= plus.webview.create('Personal_flea.html','Personal_flea.html');//后台创建webview并打开show.html
				webviewContent.addEventListener("loaded", function() { //注册新webview的载入完成事件
			        nwaiting.close(); //新webview的载入完毕后关闭等待框
			        webviewContent.show("slide-in-right",500); //把新webview窗体显示出来，显示动画效果为速度200毫秒的右侧移入动画
				}, false);
	 		}else{
//	 			toast(data.datas.error+' 订单生成失败');
	 			money_return();
	 		}
	 	},
	 	error:function(e){
	 		console.log(JSON.stringify(e));
	 	}
	 });
}

//生成订单失败  返回金额
function money_return(){
	var money_total = $('.goods_total').text();
	$.ajax({
		type:"post",
		url:apiRoot + "?act=member_buy&op=payment_return",
		data:{
			member_id:member_id,
			money_total:money_total
		},
		dataType:'json',
		success:function(data){
			if(data.code == 200){
				toast('生成订单失败！已返回支付金额至余额！');
			}else{
				alert('生成订单失败！'+data.datas.error+'请截图联系客服！');
			}
		},
		error:function(e){
			error();
		}
	});
}

function commodity_shelf(){
	$.ajax({
		type:"post",
		url:apiRoot + "?act=member_buy&op=commodity_shelf",
		data:{
			member_id:member_id,
			goods_ids:shuju
		},
		dataType:'json',
		success:function(data){
//			console.log(JSON.stringify(data));
		},
		error:function(e){
		}  
	});
}
